package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public class BaseServiceImpl<T extends BaseDomain, E extends BaseQuery> implements IBaseService<T, E> {

    @Autowired(required = false)
    protected Mapper<T> mapper;


    @Override
    public T find(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageList<T> pageResult(List<T> list) {

        return null;
    }

    @Override
    public List<T> queryAll() {
        return mapper.selectAll();
    }

    @Override
    public boolean save(T model) {
        boolean result;
        if (find(model.getId()) == null) {
            result = mapper.insert(model) > 0;
        } else {
            result = mapper.updateByPrimaryKey(model) > 0;
        }
        return result;
    }

    @Override
    public boolean delete(Long id) {
        return mapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    @Transactional
    public boolean batchDelete(Long[] ids) {
        if (ids == null || ids.length == 0) return false;
        for (Long id : ids) {
            int rows = mapper.deleteByPrimaryKey(id);
            if (rows <= 0) {
                return false;
            }
        }
        return true;
    }


}
